<template>
  <el-form :inline="true">
    <el-form-item label="部门名称">
      <el-input v-model="queryConditions.name" style="width: 200px" size="large" placeholder="请输入"
        :suffix-icon="Search" clearable />
    </el-form-item>
      <el-button type="primary" :icon="Search" @click="search">查询</el-button>
      <el-button type="primary" :icon="RefreshRight" @click="reset">重置</el-button>
    </el-form>
    <TestPage :table-data="formattedTableData" :columns="tableColumns" :current-page="pageNo" :total="allPage"
      :page-size="pageSize" @page-change="handlePageChange" @action="handleTableAction" @edit="handleEditAction"
      @delete="handleDeleteAction" />

    <!-- 弹窗显示 AddCustomer -->
    <el-dialog title="新增部门" v-model="showAddDialog" width="40%" :before-close="handleDialogClose">
      <AddDept @submit-success="handleAddSuccess" @cancel="handleDialogClose" />
    </el-dialog>
    <!-- 编辑客户弹窗 -->
    <el-dialog title="编辑部门" v-model="showEditDialog" width="40%" :before-close="handleDialogClose">
      <AddDept :department="editingDept" @submit-success="handleEditSuccess" @cancel="handleDialogClose" />
    </el-dialog>
</template>

<script setup lang="ts">
import TestPage from "@/test/TestPage.vue"
import AddDept from "./AddDept.vue";
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { ref, computed, reactive } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import type { Department } from '@/types/rs/Department';
import request from '@/util/request'
let pageNo = ref(1)
let pageSize = ref(3)
let allPage = ref(0)

//查询条件
const queryConditions = reactive({
  name: ''
})

const tableColumns = ref([
  { prop: 'id', label: '序号' },
  { prop: 'name', label: '部门' },
  { prop: 'is_delete', label: '删除状态' },
  { prop: 'createDate', label: '创建时间' },
  { prop: 'createUser', label: '创建人' },
  { prop: 'updateDate', label: '更新时间' },
  { prop: 'updateUser', label: '更新人' }


])
let tableData = ref<Department[]>([])
// 计算属性
const formattedTableData = computed(() => {
  return tableData.value.map(item => ({
    ...item,
    is_delete: item.is_delete === 0 ? '正常' : '被删除'
  }));
});

const showAddDialog = ref(false); // 新增弹窗
const showEditDialog = ref(false); // 编辑弹窗
const editingDept = ref<Department | null>(null); // 当前编辑的客户

const handlePageChange = (newPage: number) => {
  pageNo.value = newPage

  fetchData(newPage)
}


const handleTableAction = (actionName: string) => {
  console.log('触发操作:', actionName)
  // 处理具体业务逻辑
  if (actionName === 'add') {
    showAddDialog.value = true; // 打开新增弹窗
  }
}

//修改弹窗
const handleEditAction = (department: Department) => {
  editingDept.value = { ...department }; // 复制客户数据
  showEditDialog.value = true; // 打开修改弹窗
};

const handleDeleteAction = async (department: Department) => {
  try {
    console.log('[Debug] 当前部门数据:', department)
    console.log('[Debug] is_delete 类型:', typeof department.is_delete)
    await ElMessageBox.confirm('确定删除此客户？此操作不可恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    if(department.is_delete==1){
      ElMessage.error('该部门已被删除, 请勿重复删除');
      return
    }
    await request.post(`http://localhost:8888/per/dept/del?id=${department.id}`,);
    ElMessage.success('删除成功');
    await fetchData(pageNo.value); // 刷新
  } catch (error) {
    ElMessage.error('删除失败，请稍后重试');
    console.error('删除失败:', error);
  }
};

const handleAddSuccess = () => {
  showAddDialog.value = false;
  fetchData(pageNo.value); // 刷新
  ElMessage.success('新增商品成功');
};

const handleEditSuccess = () => {
  showEditDialog.value = false;
  editingDept.value = null;
  fetchData(pageNo.value); // 刷新表格
  ElMessage.success('更新商品成功');
};

const handleDialogClose = () => {
  ElMessageBox.confirm('确定关闭新增客户窗口？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    showAddDialog.value = false; // 确认关闭
    showEditDialog.value = false;
  })
};

//查询
const search = () => {
  pageNo.value = 1; // 重置到第一页
  fetchData(1);
};

//重置
const reset = () => {

}


async function fetchData(page: number) {
  try {
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', pageSize.value.toString());
    params.append('combine', queryConditions.name);

    let response = await request.post('/per/dept/getPage', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    tableData.value = response.data.data.list || [];
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    tableData.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}

fetchData(1)
</script>


<style scoped></style>
